/*
 * @Author: hongbin
 * @Date: 2022-03-30 14:55:59
 * @LastEditors: hongbin
 * @LastEditTime: 2022-04-06 21:37:24
 * @Description: 选中元素的属性设置面板
 */
import { FC, ReactElement, useCallback } from "react";
import styled from "styled-components";
import { useElementContext } from "../../context/ElementContext";
import { ElementNode } from "../ElementProvider/ElementList";
import PropItem from "./PropItem";

interface IProps {}

const ElementProps: FC<IProps> = (): ReactElement => {
  const { current, setCurrent, pageAxis, setElementTree } = useElementContext();

  const toggleUnit = useCallback(
    (property: string, unit: string) => () => {
      setElementTree((prev) => {
        const tree = [...prev];

        tree.some((node) => {
          if (node.key === current!.key) {
            node.unit[property] = unit;
            setCurrent({ ...node, unit: { ...node.unit, [property]: unit } });
            return true;
          }
          return false;
        });

        return tree;
      });
    },
    [current, setElementTree, setCurrent]
  );

  if (!current) return <></>;

  const { name, style, unit } = current;

  //位置转换成预览模式的值
  const { left, top, ...styles } = style;

  return (
    <Container>
      <span>{name}属性面板</span>
      <PropItem
        name="left"
        // val={topTranslate(unit["left"], left, pageAxis.minX, pageAxis.width, pageAxis.height)}
        val={left}
        unit={unit["left"]}
        onToggleUnit={toggleUnit}
      />
      <PropItem
        name="top"
        // val={leftTranslate(unit["top"], top, pageAxis.minY, pageAxis.width, pageAxis.height)}
        val={top}
        unit={unit["top"]}
        onToggleUnit={toggleUnit}
      />
      {Object.entries(styles).map(([key, val]) => (
        <PropItem key={key} name={key} val={val} unit={unit[key]} onToggleUnit={toggleUnit} />
      ))}
    </Container>
  );
};

export default ElementProps;

const topTranslate = (unit: string, val: number, x: number, w: number, h: number) =>
  ((((unit === "vw" ? window.bodyWidth : window.bodyHeight) / 100) * val - x) / (unit === "vw" ? w : h)) * 100;

const leftTranslate = (unit: string, val: number, y: number, w: number, h: number) =>
  ((((unit === "vw" ? window.bodyWidth : window.bodyHeight) / 100) * val - y) / (unit === "vw" ? w : h)) * 100;

const Container = styled.div`
  background-color: #f6f3ed;
  flex: 1;
  font-size: 1vw;
  span {
    font-weight: bold;
    letter-spacing: 1px;
  }
  button {
    border: none;
    padding: 2px 5px;
  }
  p {
    color: #444;
  }
`;
